import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from struct import unpack
from sklearn import svm
import time
from sklearn.externals import joblib
from sklearn.decomposition import PCA

#读取图片类型，返回数组,一行代表一张图片
def read_image(path):
    with open(path, 'rb') as f:
        magic, num, rows, cols = unpack('>4I', f.read(16))
        img = np.fromfile(f, dtype=np.uint8).reshape(num, 784)
    return img

#读取标签类型，返回数组、
def read_label(path):
    with open(path, 'rb') as f:
        magic, num = unpack('>2I', f.read(8))
        lab = np.fromfile(f, dtype=np.uint8)
    return lab

#读取数据集
train=read_image('train-images.idx3-ubyte')
test=read_image('t10k-images.idx3-ubyte')
#aa=normalize_image(a)
train_label=read_label('train-labels.idx1-ubyte')
test_label=read_label('t10k-labels.idx1-ubyte')
#读取训练集第一张图片，转维度
#rt=train[0:5,:].reshape(28,28)
for i in range(len(test)):
    x=test[i,:].reshape(28,28)
for j in range(len(train)):
    y=train[j,:].reshape(28,28)

#将数据转化为数组
#x_train=y.as_matrix()
y_train=pd.DataFrame(np.array(train_label).reshape(60000,1)).as_matrix()
#x_test=x.as_matrix()
y_test=pd.DataFrame(np.array(test_label).reshape(10000,1)).as_matrix()

#img_gyh=np.round(train/255)#进行归一化
#img_arr=np.reshape(img_gyh,(1,-1))#1*784

x_train=train.reshape(60000,784).astype('float32')
x_test=test.reshape(10000,784).astype('float32')
#将数据归一化
x_train_gyh=x_train/255
x_test_gyh=x_test/255

#使用svm
## 使用 “高斯核”，gamma 系数取 0.001
print(time.strftime('%Y-%m-%d %H:%M:%S'))
from sklearn.svm import SVC
svm = SVC(kernel='rbf', C=10, gamma=0.1)	# 使用 “高斯核”，gamma 系数取 0.001
svm.fit(x_train_gyh,y_train)


'''#0.1
print(time.strftime('%Y-%m-%d %H:%M:%S'))
from sklearn.svm import SVC
svm = SVC(kernel='rbf', C=10, gamma=0.1)	# 使用 “高斯核”，gamma 系数取 0.001
svm.fit(x_train_gyh,y_train)
'''
print("Accuracy on training set: {:.3f}".format(svm.score(x_train_gyh,y_train)))
print("Accuracy on test set: {:.3f}".format(svm.score(x_test_gyh,y_test)))


#使用提取好的特征数据进行拟合
from sklearn.decomposition import PCA
pca = PCA(n_components=40, whiten=True, random_state=0).fit(x_train)
X_train_pca = pca.transform(x_train_gyh)
X_test_pca = pca.transform(x_test_gyh)

# 使用 SVM
from sklearn.svm import SVC
t1=time.time()
svm = SVC(kernel='rbf', C=10, gamma=0.1)
svm.fit(X_train_pca, y_train)

# 准确率
# 训练集的准确率
t2=time.time()
SVMfit=float(t2-t1)
print('time taken:{}second'.format(SVMfit))
print(svm.score(X_train_pca, y_train))
# 测试集的准确率
print(svm.score(X_test_pca, y_test))

